package com.ms.yk;

import android.app.Activity;
import android.app.Application;

import java.util.ArrayList;
import java.util.List;

public class SmsApplication extends Application {
    private static List<Activity> activities = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public static synchronized void addActivity(Activity activity) {
        int index = indexOfActivity(activity);
        if (index != -1) {
            activities.remove(index);
        }
        if (activities.size() > 0)
            activities.add(0, activity);
        else
            activities.add(activity);
    }

    public static synchronized void removeActivity(Activity activity) {
        int index = indexOfActivity(activity);
        if (index != -1) {
            activities.remove(index);
            if (!activity.isDestroyed())
                activity.finish();
        }
    }

    public static synchronized void removeActivityExist(Activity activity) {
        int index = indexOfActivity(activity);
        if (index != -1) {
            activities.remove(index);
            while (activities.size() > 0) {
                Activity a = activities.get(0);
                activities.remove(0);
                a.finish();
            }
            activities.add(activity);
        }
    }

    public static void exit() {
        while (activities.size() > 0) {
            Activity activity = activities.get(0);
            activities.remove(0);
            activity.finish();
        }
        System.exit(-1);
    }

    public static int indexOfActivity(Activity activity) {
        if (activity != null) {
            for (int i = 0; i < activities.size(); i++) {
                if (activity.getClass().equals(activities.get(i).getClass())) {
                    return i;
                }
            }
        }
        return -1;
    }
}
